package com.itheima.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.dto.UserDto;
import com.itheima.youdianda.dto.UserRole;
import com.itheima.youdianda.entity.SysRole;
import com.itheima.youdianda.entity.SysRoleMenu;
import com.itheima.youdianda.entity.SysUser;
import com.itheima.youdianda.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.service.SysRoleMenuService;
import com.itheima.youdianda.service.SysRoleService;
import com.itheima.youdianda.service.SysUserService;
import com.itheima.youdianda.util.MyPage;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDto getUserDto(String userId) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getId,userId);
        SysUser sysUser = this.getOne(wrapper);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(sysUser,userDto,"role_id");
        String[] roleIds = sysUser.getRole_id().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        userDto.setRole_id(roleIds);
        String id = sysUser.getId();
        LambdaQueryWrapper<SysRoleMenu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysRoleMenu::getMenu_id,id);
        String roleId = sysRoleMenuService.list(wrapper1).get(0).getRole_id();
        LambdaQueryWrapper<SysRole> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SysRole::getId,roleId);
        List<SysRole> list = sysRoleService.list(wrapper2);
        List<String> role_name = new ArrayList<>();
        for (SysRole sysRole : list) {
            role_name.add(sysRole.getName());
        }
        userDto.setRolename(role_name);
        return userDto;
    }

    @Override
    public MyPage<UserRole> listByPage(String login_name, String status, String phone, String page, String limit) {
        Page<SysUser> userPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(status),SysUser::getStatus,status)
                .like(StringUtils.isNotEmpty(login_name),SysUser::getLogin_name,login_name)
                .like(StringUtils.isNotEmpty(phone),SysUser::getPhone,phone);
// 根据条件分页查询
        this.page(userPage,wrapper);
        List<SysUser> records = userPage.getRecords();

        List<UserRole> userRoleRecords = new ArrayList<>();
        for (SysUser record : records) {
            UserRole userRole = new UserRole();
            BeanUtils.copyProperties(record,userRole,"role_id");
            String[] roleIds = record.getRole_id().replace("[", "")
                    .replace("]", "")
                    .replace("\"", "")
                    .split(",");
            List<String> roleIdList = new ArrayList<>();
            Collections.addAll(roleIdList,roleIds);
            // 存入 role_id 集合
            userRole.setRole_id(roleIdList);
            List<String> roleNameList = sysRoleService.getRoleNameList(roleIdList);
            // 存入 rolename 集合
            userRole.setRolename(roleNameList);
            userRoleRecords.add(userRole);
        }

// 调用MyPage工具类帮我们封装分页数据给前端
        return MyPage.formatPage(userPage, userRoleRecords);
    }

    @Override
    public void updateByIdWithRoleName(UserRole userRole) {
        SysUser sysUser = userRoleToSysUser(userRole);
        this.updateById(sysUser);
    }

    private SysUser userRoleToSysUser(UserRole userRole) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userRole,sysUser,"role_id");
        String roleIdString="[\"";
        if (userRole.getRole_id()!=null) {
            for (int i = 0; i < userRole.getRole_id().size(); i++) {
                if (userRole.getRole_id().size() - 1 == i) {
                    roleIdString += (userRole.getRole_id().get(i) + "\"]");
                } else {
                    roleIdString += (userRole.getRole_id().get(i) + ",");
                }
            }
        }
        sysUser.setRole_id(roleIdString);
        return sysUser;
    }

    @Override
    public UserRole getByIdWithRoleName(String id) {
        UserRole userRole = new UserRole();
        SysUser user = this.getById(id);
        BeanUtils.copyProperties(user,userRole,"role_id","password");
        String[] roleIds = user.getRole_id().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> roleIdList = new ArrayList<>();
        Collections.addAll(roleIdList,roleIds);
// 存入 role_id 集合
        userRole.setRole_id(roleIdList);
        List<String> roleNameList = sysRoleService.getRoleNameList(roleIdList);
// 存入 rolename 集合
        userRole.setRolename(roleNameList);
        userRole.setPassword("");
        return userRole;
    }

    @Override
    public void add(UserRole userRole) {
        SysUser sysUser = userRoleToSysUser(userRole);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        // sysUser.setId(UUID.randomUUID().toString());
        this.save(sysUser);
    }
}
